import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class MyBlockingQueue {
    private static final int MAX_SIZE = 1000;
//    private List<Integer> list = new LinkedList<>();
//    private Object locker = new Object();
//    public int take() throws InterruptedException {
//
//        if (list.size() == 0) {
//            synchronized (locker) {
//                locker.wait();
//            }
//        }
//        return list.get(list.size() - 1);
//    }
//
//    public void put(int val) {
//        if ()
//    }

    private int[] items = new int[MAX_SIZE];
    // [head , tail)
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;
    synchronized public void put(int val) throws InterruptedException {
        if (size == items.length) {
            this.wait();
        }
        items[tail] = val;
        tail++;
        if (tail == items.length) {
            tail = 0;
        }

        size++;

        this.notify();
    }
    synchronized public Integer take () throws InterruptedException {
        if (size == 0) {
            this.wait();
        }
        int val = items[head];
        size--;
        head++;
        if (head == items.length) {
            head = 0;
        }
        this.notify();
        return val;
    }

    public int getHead() {
        return head;
    }

    public int getTail() {
        return tail;
    }
}

class Main1 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue myBlockingQueue =
                new MyBlockingQueue();
        Thread t1 = new Thread(()-> {
            int result = 3;
            int head = 0;
            while (true) {
                try {
                    head = myBlockingQueue.getHead();
                    result = myBlockingQueue.take();

                    System.out.println("消费元素" + result + "head" + head);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(()-> {
           int val = 0;
           int tail = 0;
           while (true) {
               try {

                   myBlockingQueue.put(val);
                   tail = myBlockingQueue.getTail();
                   System.out.println("生成元素" + val + "tail" + tail);
                   val++;
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        t1.start();
        Thread.sleep(3000);
        t2.start();
    }
}
